package com.xinghen.ace.common.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xinghen
 * @ClassName: ThreadContextHelper
 * @Package: com.xinghen.ace.common.util
 * @Description 线程本地变量存取器
 * @create 2018-05-04 10:33
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreadContextHelper {

    private static final MapThreadLocal CONTEXT_HOLDER = new MapThreadLocal();

    public static Map<String, Object> getContext() {
        return CONTEXT_HOLDER.get();
    }

    public static void set(String key, Object value) {
        getContext().put(key, value);
    }

    public static Object get(String key) {
        return getContext().get(key);
    }

    public static void remove() {
        getContext().clear();
    }

    private static class MapThreadLocal extends ThreadLocal<Map<String, Object>> {

        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<String, Object>(1 << 4) {
                @Override
                public Object put(String key, Object value) {
                    return super.put(key, value);
                }
            };
        }
    }

}
